import { Button, Form, Input, message } from 'antd';
import styles from './index.less';
import { useEffect, useState } from 'react';
import { useForm } from 'antd/es/form/Form';
import { getUserInfo, postLogin, postRegister } from '@/services/login';
import { history, useParams } from '@umijs/max';

const Login = () => {
    const isRegister = useParams().isRegister;
    useEffect(() => {
        if (isRegister || isRegister === 'true') {
            setRegister(true)
        }
    }, [isRegister])
    const [register, setRegister] = useState(false)
    const [form] = useForm()
    const registerHandle = () => {
        const params = form.getFieldsValue()
        postRegister(params).then(res => {
            if (res.code === 200) {
                message.success('注册成功')
                setRegister(false)
            } else {
                message.error(res.message)
            }
        })
    }
    const login = () => {
        const params = form.getFieldsValue()
        postLogin(params).then(res => {
            if (res.code === 200) {
                localStorage.setItem('token', res.data)
                getUserInfo().then((res) => {
                    localStorage.setItem('userInfo', JSON.stringify(res.data))
                    localStorage.setItem('isLogin', 'true')
                    history.push('/home')
                })
                message.success('登陆成功')
            } else {
                message.error(res.message)
            }
        })
    }
    return (
        <div className={styles.page}>
            <div className={styles.login}>
                <div style={{marginBottom: 20}}>登陆 / 注册</div>
                <Form
                name="basic"
                form={form}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
                initialValues={{ remember: true }}
                autoComplete="off"
                labelAlign="left"
                >
                <Form.Item
                label="用户名"
                name="phone"
                rules={[{ required: true, message: '请输入用户名' }, 
                    {
                        pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                        message: '用户名只能使用手机号格式',
                      }, 
                ]}
                >
                    <Input />
                </Form.Item>

                <Form.Item
                label="密码"
                name="password"
                rules={[{ required: true, message: '请输入密码' }, {max: 100, message: '密码长度不能超过100' }, {min: 6, message: '密码长度不能小于6' }]}
                >
                    <Input.Password />
                </Form.Item>

                {
                    register && 
                    <Form.Item
                    label="再次输入密码"
                    name="confirm_password"
                    rules={[{ required: true, message: '请再次输入密码' },
                        {max: 100, message: '密码长度不能超过100' },
                        ({ getFieldValue }) => ({
                            validator(_, value) {
                              if (!value || getFieldValue('password') === value) {
                                return Promise.resolve();
                              }
                              return Promise.reject(new Error('两次输入密码不一致!'));
                            },
                          }),
                    ]}
                    >
                        <Input.Password />
                    </Form.Item>
                }

                <Form.Item label={null}>
                    {
                        !register ? 
                        <>
                            <Button style={{ marginRight: 10}} onClick={login} type="primary" htmlType="submit">
                                登陆
                            </Button>
                            <Button htmlType="button" onClick={() => setRegister(true)}>
                                注册
                            </Button>
                        </> : 
                        <>
                            <Button style={{ marginRight: 10}} type="primary" onClick={() => setRegister(false)}>
                                返回登陆
                            </Button>
                            <Button htmlType="button" onClick={registerHandle}>
                                注册
                            </Button>
                        </>
                    }
                    
                </Form.Item>
            </Form>
            </div>
        </div>
    )
}

export default Login